<?php

namespace backend\controllers;

use Yii;
use common\models\Expert\Expert;
use common\models\Expert\ExpertSearch;
use common\models\Invitation\Invitation;
use common\models\Invitation\InvitationSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use zhongkefu\zhongkefu;
use common\models\adminlog\AdminLog;
use zhongkefu\helpers\Utils;
use yii\web\UploadedFile;
use kartik\file\FileInput;//图片上传
use zhongkefu\helpers\Excelwriter;


/**
 * ExpertController implements the CRUD actions for Expert model.
 */
class ExpertController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Expert models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ExpertSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Expert model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Expert model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Expert();
         if ($model->load(Yii::$app->request->post()) ) {
            $username = Yii::$app->request->post()['Expert']['username'];
            $model->zhaopian = UploadedFile::getInstance($model, 'zhaopian');
            if($model->zhaopian){           
                $siteRoot = Yii::$app->params['expimg'];
                $json = Utils::uploadfile($_FILES['Expert']['tmp_name']['zhaopian'],$_FILES['Expert']['name']['zhaopian'],$siteRoot);
                $model->zhaopian = $json;   
                        
            }

            if($model->save()){
                Adminlog::addlog(yii::$app->user->id, '添加广告 '.$username);
                return $this->redirect(['view', 'id' => $model->id]);
            }else{
                Yii::$app->session->setFlash('warning', Yii::t('app', '图片不能为空'));
                return $this->render('create', [
                    'model' => $model,
                ]);
            }
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }




    }

    /**
     * Updates an existing Expert model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
     $model = $this->findModel($id);
         //上传图片插件
         if ($model->load(Yii::$app->request->post()) ) {

            $model->zhaopian = UploadedFile::getInstance($model, 'zhaopian');
            if($model->zhaopian){
                $siteRoot = Yii::$app->params['expimg'];

                $json = Utils::uploadfile($_FILES['Expert']['tmp_name']['zhaopian'],$_FILES['Expert']['name']['zhaopian'],$siteRoot);
                //var_dump($json);die();
                $model->zhaopian = $json;                
            }
             if (!$model->zhaopian) {
                $new = $this->findModel($id);
                $model->zhaopian = $new->zhaopian;
            }
            if($model->save()){
                $username = Yii::$app->request->post()['Expert']['username'];
                //var_dump($username);die();
                return $this->redirect(['view', 'id' => $model->id]);
            }else{
                return $this->render('update', [
                    'model' => $model,
                ]);
            }
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
      




    }

    /**
     * Deletes an existing Expert model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Expert model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Expert the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Expert::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
      /**
     * 删除按钮
     * If update is successful, the browser will be redirected to the 'index' page.
     * @return mixed
     */
    public function actionAlldelete()
    {
        $artname="";
        if(isset(zhongkefu::$app->request->post()["checkboxid"])){
            $ids = zhongkefu::$app->request->post()["checkboxid"];
            $ids = explode(',',$ids);
            foreach($ids as $val){
                $model = Expert::findOne(['id' => $val]);
                $artname .= $model->username.",";
            }
            $artname = substr($artname,0,-1);
            foreach($ids as $id){
                $model = Expert::findOne(['id' => $id]);
                $this->findModel($id)->delete();
            }
            Adminlog::addlog(yii::$app->user->id, "批量删除广告 ".$artname);
            return true;
        }
    }


    //专家数据导入
    public function actionDaoru() {

        header("Content-type:text/html;charset=utf-8");
        $new_file = time().mt_rand(1000,9999).'.xls';
        $siteRoot =  Yii::$app->params['articleimg'];
        $a = move_uploaded_file($_FILES['excelfile']["tmp_name"], $siteRoot.$new_file);
        $objPHPExcel = new \PHPExcel();
        $sheet = 0; // 默认第一个sheet
        $PHPExcel = \PHPExcel_IOFactory::load($siteRoot.$new_file);
        $currentSheet = $PHPExcel->getSheet(0); /* * 读取excel文件中的第一个工作表 */
        $allColumn = $currentSheet->getHighestColumn();/**取得最大的列号*/
        $allRow = $currentSheet->getHighestRow(); /* * 取得一共有多少行 */
        \PHPExcel_Cell::columnIndexFromString(); //字母列转换为数字列 如:AA变为27
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow = $currentRow + 1) {
            //将excl表中的值赋给变量，然后将变量写入数据库
            $username = trim($currentSheet->getCellByColumnAndRow(1, $currentRow)->getValue()); //姓名
            $password = trim($currentSheet->getCellByColumnAndRow(2, $currentRow)->getValue()); //密码
            $sex = trim($currentSheet->getCellByColumnAndRow(3, $currentRow)->getValue()); //性别
            $phone = trim($currentSheet->getCellByColumnAndRow(4, $currentRow)->getValue()); //手机
            $zhaopian = trim($currentSheet->getCellByColumnAndRow(5, $currentRow)->getValue()); //照片
            $telephone = trim($currentSheet->getCellByColumnAndRow(6, $currentRow)->getValue()); //固定电话
            $email = trim($currentSheet->getCellByColumnAndRow(7, $currentRow)->getValue()); //邮箱
            $compamy = trim($currentSheet->getCellByColumnAndRow(8, $currentRow)->getValue()); //公司
            $zhiwu = trim($currentSheet->getCellByColumnAndRow(9, $currentRow)->getValue()); //职务
            $birthday = trim($currentSheet->getCellByColumnAndRow(10, $currentRow)->getValue()); //身份证
            $comefrom = trim($currentSheet->getCellByColumnAndRow(11, $currentRow)->getValue()); //开户行
            $bnumber = trim($currentSheet->getCellByColumnAndRow(12, $currentRow)->getValue()); //银行卡号
            $loc_town = trim($currentSheet->getCellByColumnAndRow(13, $currentRow)->getValue()); //专业领域
            $chengguo = trim($currentSheet->getCellByColumnAndRow(14, $currentRow)->getValue()); //文章成果
            $reason = trim($currentSheet->getCellByColumnAndRow(15, $currentRow)->getValue()); //学习及工作经历

            //将信息写入expert表中
            $experts = new Expert();
            $experts->username = $username;
            $experts->password = $password;
            $experts->sex = $sex ;
            $experts->phone = $phone;
            $experts->zhaopian = $zhaopian;
            $experts->telephone = $telephone;
            $experts->email = $email;
            $experts->compamy = $compamy;
            $experts->zhiwu = $zhiwu;
            $experts->birthday = $birthday;
            $experts->comefrom = $comefrom;
            $experts->bnumber = $bnumber;
            $experts->loc_town = $loc_town;
            $experts->chengguo = $chengguo;
            $experts->reason = $reason;
            $ok = $experts->save(false);
            if(!$ok){
                throw new ErrorException("导入信息失败");
            }


        }
        Yii::$app->getSession()->setFlash('success', '导入成功');
        return $this->redirect(['index']);
    }



}
